﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _测试更新
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        SqlConnection conn = new SqlConnection("server=.;database=SqlData;uid=sa;pwd=sql@2012");
        SqlDataAdapter adapter;//声明SqlDataAdapter adapter对象
        private void Form1_Load(object sender, EventArgs e)
        {
            adapter = new SqlDataAdapter("Select * from PersonData", conn);
            DataSet ds = new DataSet();
            adapter.Fill(ds);
            dataGridView1.DataSource = ds.Tables[0];
        }

        private DataTable dbconn(string sql)
        {
            conn.Open();
            this.adapter = new SqlDataAdapter(sql, conn);
            DataTable dtSelect = new DataTable();
            this.adapter.Fill(dtSelect);
            conn.Close();
            return dtSelect;
        }

        private Boolean dbUpdate()
        {
            string sql = "Select * from PersonData";
            DataTable dtUpdate = new DataTable();
            dtUpdate = this.dbconn(sql);
            dtUpdate.Rows.Clear();
            DataTable dtShow = new DataTable();
            dtShow = (DataTable)this.dataGridView1.DataSource;
            for (int i = 0; i < dtShow.Rows.Count; i++)
            {
                dtUpdate.ImportRow(dtShow.Rows[i]);
            }
            try
            {
                this.conn.Open();
                SqlCommandBuilder CommandBuilder;
                CommandBuilder = new SqlCommandBuilder(this.adapter);
                this.adapter.Update(dtUpdate);
                this.conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
                return false;
            }
            dtUpdate.AcceptChanges();
            dtUpdate.Dispose();
            return true;

        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dbUpdate())
            {
                dataGridView1.DataSource = dbconn("Select * from PersonData");
                MessageBox.Show("修改成功！");
            }
        }

        private void EditToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dbUpdate())
            {
                dataGridView1.DataSource = dbconn("Select * from PersonData");
                MessageBox.Show("修改成功！");
            }
        }
    }


}
